package com.glsc.ngateway.opmanage.service.document;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.glsc.ngateway.common.api.common.ex.Result;
import com.glsc.ngateway.common.api.common.utils.CommonUtils;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.document.DocumentInfo;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.document.DocumentRepository;
import com.glsc.ngateway.opmanage.aspect.UserCache;
import com.glsc.ngateway.opmanage.utils.RequestTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class DocumentService {
    private List<String> allowFileTypeList = new ArrayList<>(Arrays.asList("jpg", "jpeg", "gif", "png", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"));

    @Value("${opmanage.nas.path.commonfile}")
    String documentNasPath = "";

    @Resource
    private RequestTool requestTool;

    @Resource
    private DocumentRepository documentRepository;

    @Resource
    private UserCache userCache;

    /**
     * 保存档案信息
     *
     * @param documentInfo
     * @return
     */
    public DocumentInfo save(DocumentInfo documentInfo) {
        return documentRepository.save(documentInfo);
    }


    /**
     * 根据文件id查找文件信息
     *
     * @param docId
     * @return
     */
    public DocumentInfo findById(Integer docId) {
        Optional<DocumentInfo> optional = documentRepository.findById(docId);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    public PlatformResponse uploadFile(MultipartFile file) throws IOException {

        String oFileName = file.getOriginalFilename();
        log.info("上传的文件名：" + oFileName);
        if (null == oFileName || oFileName.length() < 4) {
            return PlatformResponse.failedMsg("上传文件名不合法，文件名至少4个字符");
        }
        oFileName = CommonUtils.getFileNameFromPath(oFileName);//去除可能的文件路径（解决IE下带路径问题）

        int lastPos = oFileName.lastIndexOf(".");//lastPos=-1,没有文件类型后缀

        String fileSuffix = null;
        if (lastPos > 0 && lastPos < oFileName.length()) {
            fileSuffix = oFileName.substring(lastPos + 1).toLowerCase();
        }
        if (StrUtil.isEmpty(fileSuffix)) {
            fileSuffix = "";
        }
        fileSuffix = fileSuffix.toLowerCase();
        log.info("上传文件类型" + fileSuffix + "，文件全称：" + oFileName);
        if (!allowFileTypeList.contains(fileSuffix)) {
            return PlatformResponse.failedMsg("只能上传jpg/jpeg/gif/png/pdf/doc/xls/ppt类型的文件");
        }

        if (file.getSize() > 1024 * 1000 * 100) {
            return PlatformResponse.failedMsg("档案不得大于100M，实际上传文件大小为" + file.getSize() / (1000.0 * 1024));
        }


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String path = documentNasPath + time + "/" + uuid + oFileName;


        File destFile = new File(path);
        try {
            log.info("存储文件至目录" + destFile.getAbsolutePath());
            FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
        } catch (IOException e) {
            String errMsg = "上传产品档案失败，原因：" + e.getLocalizedMessage();
            log.error(errMsg, e);
            return PlatformResponse.failedMsg(errMsg);
        }

        Digester digester = new Digester(DigestAlgorithm.MD5);
        String md5Value = digester.digestHex(destFile);

        DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setFileName(oFileName);
        documentInfo.setChecksum(md5Value);
        documentInfo.setFilePath(path);
        this.initDocCreatorInfo(documentInfo);//初始化上传人信息

        DocumentInfo documentInfoDb = this.save(documentInfo);

        //以下接口返回，为前端FileTableForm控件约定
        Map<String, Object> result = new HashMap<>();
        result.put("status", 0);
        result.put("id", documentInfoDb.getDocId());
        result.put("docType", documentInfoDb.getDocType());
        result.put("checksum", documentInfoDb.getChecksum());
        result.put("fileName", documentInfoDb.getFileName());
        result.put("filePath", documentInfoDb.getFilePath());
        return PlatformResponse.successData(result);
    }

    /**
     * 设置附件上传人信息
     * * *
     */
    public void initDocCreatorInfo(DocumentInfo documentInfo) {
        if (documentInfo == null) {
            return;
        }

        //获取当前操作人
        String uploadOperator = CommonUtils.getString(requestTool.getAccountFromRequest(), "");
        if (StrUtil.isEmpty(uploadOperator)) {
            return;
        }

        //增加附件创建上传人信息
        documentInfo.setCreateOperator(requestTool.getAccountFromRequest());
        if (StrUtil.isNotEmpty(uploadOperator)) {
            User createUser = userCache.get(uploadOperator);
            if (createUser != null) {
                documentInfo.setCreateOperatorName(createUser.getName());
            }
        }
    }


}
